import ctime from '@/components/changeTime.vue'
import carInfo from '@/components/acessory/carInfo'

export default {
  components: {
    ctime,
    carInfo,
  },
  data() {
    return {
      type: '', //0新增 1编辑
      id: '', //询价单id
      value: 1, //进步器初始值
      comtupptr: false, //是否显示删除按钮
      Pressb: false,
      numberimgwg: true, //判断默认图
      showimg: false, //上传图片弹框
      Productddms: '', //商品详情描述
      quality: ['不限', '原厂', '品牌', '拆车件', '其他'],
      invoice: ['不开票', '开票'],
      //时间
      showsc: false,
      Production: '',
      modesc: 'time',
      defaultTimesc: new Date().toISOString().slice(0, 10),
      paramssc: {
        year: true,
        month: true,
        day: true,
      },
      //收获地址
      addresslist: {},
      currentindex: 0, //当前index
      Qualityselect: 0, //品质选择结果_单选
      Invoiceselect: 0, //发票选择结果
      showxj: false, //取消询价
      Selectresult: [], //配件列表
      SelectresultStr: [], //配件列表，图片转字符串后
      Brandinformation: {}, //车辆信息
      pageLoading: false, //初始化加载效果
    }
  },
  onLoad(e) {
    //1:发布询价   120：编辑删除询价
    this.type = e.type
    if (e.type == '0') {
      uni.setNavigationBarTitle({
        title: '新建询价',
      })
      this.getAddress()
      this.$nextTick(() => {
        this.pageLoading = true
      })
    } else if (e.type == '1') {
      uni.setNavigationBarTitle({
        title: '编辑询价',
      })
      this.id = e.id
      this.getInfo(e.id)
    }

    // 选择地址
    uni.$on('Newinquiry', (data) => {
      Object.assign(this.addresslist, data)
    })
  },
  onShow() {
    if (this.$store.state.accessory.selectresult.length > 0) {
      this.Selectresult = this.$store.state.accessory.selectresult
    }
    if (this.$store.state.accessory.carInfo) {
      this.Brandinformation = this.$store.state.accessory.carInfo
    }
  },
  methods: {
    // 获取询件详情
    getInfo(id) {
      console.log(222)
      this.$api.accessory
        .getCarPartOfferByCarPartId({
          id: id,
        })
        .then((res) => {
          this.Brandinformation = {
            bid: res.data.brand_Id,
            brand: res.data.brand_Name,
            brand_Logo: '/goodimg/brandimg/' + res.data.brand_Id + '.png',
            cartypeid: res.data.car_Type_Id,
            cartypename: res.data.car_Type_Name,
            id: res.data.configuration_Id,
            key: `${res.data.brand_Id} ${res.data.car_Type_Id}${res.data.configuration_Id}`,
            name: res.data.configuration_Name,
            vin: res.data.vin_No,
          }
          this.Selectresult = res.data.carPartDetails.map((item) => {
            item.images = item.images ? JSON.parse(item.images) : []
            return item
          })
          this.Qualityselect = res.data.character_Type
          this.Invoiceselect = res.data.is_Need_Invoice ? 1 : 0
          this.addresslist = res.data.receiver_Address_Json
          if (res.data.quote_Status === 10) {
            const date = new Date(res.data.effective_Time)
            this.Production =
              date.getFullYear() +
              '-' +
              (date.getMonth() + 1) +
              '-' +
              date.getDate()
          }
          console.log(this.Qualityselect)
          console.log(111)
          this.pageLoading = true
        })
        .catch((e) => {
          this.pageLoading = true
        })
    },

    // 默认地址
    getAddress() {
      this.$api.common
        .addressList({
          PageIndex: 1,
          PageSize: 1,
        })
        .then((res) => {
          if (res.data.list.length) {
            this.addresslist = res.data.list[0]
          } else {
            this.$set(this.addresslist, 'address', '您还没有收货地址，请添加')
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },
    //长按显示删除
    logoTime() {
      this.Pressb = true
    },

    //添加配件
    Addaccesclick() {
      this.$store.commit('accessory/setSelectresult', this.Selectresult)
      if (this.type === '0') {
        uni.navigateBack({
          delta: 1,
        })
      } else {
        this.$store.commit('accessory/setCarInfo', this.Brandinformation)
        uni.navigateTo({
          url: '/pages_findAccessory/selectCategory/selectCategory?type=1',
        })
      }
    },
    //品质选择
    selectQuality(index) {
      this.Qualityselect = index
    },
    //是否开票
    Invoiceselection(index) {
      this.Invoiceselect = index
    },
    //删除图片
    deletecom(e) {
      this.Selectresult.forEach((item, index) => {
        if (index === this.currentindex) {
          item.images.splice(e, 1) //取消
        }
      })
      this.numberimgwg = true
    },
    //取消删除
    quxiaosc() {
      this.Pressb = false
    },
    // 选择上传图片方式
    UploadIDcardImgtk(e) {
      this.currentindex = e
      this.showimg = true //打开上传图片弹框
    },
    //跳转收获地址
    Harvestaddress() {
      uni.navigateTo({
        url: '/pages_common/meShipAddress/meShipAddress?type=110',
      })
    },
    //取消询价
    Cancelinquiry() {
      this.showxj = true
    },

    //我在想想
    woxiangx() {
      this.showxj = false
    },
    //确认取消询价
    requerqx() {
      this.$api.accessory
        .cancelCarPart({
          id: this.id,
          quote_Status: 0,
        })
        .then((res) => {
          this.showxj = false
          uni.navigateBack()
        })
        .catch((e) => {
          console.log(e)
        })
    },

    //选择图片  type 0 相册 1 拍照
    uploadIDcardImg(type) {
      this.showimg = false
      uni.chooseImage({
        count: 5,
        sizeType: ['original', 'compressed'],
        sourceType: type ? ['camera'] : ['album'],
        success: (result) => {
          this.$api.files
            .uploadImg({
              filePath: result.tempFilePaths[0],
            })
            .then((res) => {
              this.fanhuiimg = res.baseUrl + res.url
              this.FanHUIimgs(this.fanhuiimg)
            })
            .catch((err) => {
              console.log(err)
              uni.showToast({
                title: '图片上传失败，请稍后重试',
                icon: 'none',
              })
            })
        },
      })
    },

    //上传图片赋值
    FanHUIimgs(res) {
      this.Selectresult[this.currentindex].images.push(res)
      this.showimg = true
      this.showimg = false
    },
    //有效期
    valclick() {
      this.showsc = true
    },
    //有效时间
    confirmsc(e) {
      this.Production = ''
      if (this.mode == 'time') {
        if (this.paramssc.year) this.Production += e.year
        if (this.paramssc.month) this.Production += '-' + e.month
        if (this.paramssc.day) this.Production += '-' + e.day
      } else {
        const now = new Date(new Date().toLocaleDateString()).getTime()
        const selDateStr = `${e.year}/${e.month}/${e.day} 00:00`
        const selDate = new Date(selDateStr).getTime()
        if (selDate > now) {
          this.Production = `${e.year}-${e.month}-${e.day}`
          this.showsc = false
        } else {
          uni.showToast({
            title: '有效期不能早于今天',
            icon: 'none',
          })
        }
      }
    },
    closeTime() {
      this.showsc = false
    },
    //确认
    chakanwxc() {
      if (!this.verifyData()) {
        return
      }
      const params = {
        id: this.id,
        vin_No: this.Brandinformation.vin ? this.Brandinformation.vin : '',
        brand_Id: this.Brandinformation.bid,
        brand_Logo:
          this.Brandinformation.brand_Logo || this.Brandinformation.brand_logo,
        brand_Name: this.Brandinformation.brand,
        car_type_id: this.Brandinformation.cartypeid,
        car_Type_Name: this.Brandinformation.cartypename,
        configuration_Id:
          this.Brandinformation.id || this.Brandinformation.configuration_id,
        character_Type: this.Qualityselect,
        is_Need_Invoice: this.Invoiceselect ? true : false,
        effective_Time: this.Production,
        configuration_Name: this.Brandinformation.name,
        receiver_Address_Id: this.addresslist.id,
        receiver_Address_Json: {
          id: this.addresslist.id,
          name: this.addresslist.name,
          mobile: this.addresslist.mobile,
          province: this.addresslist.mcprovince,
          city: this.addresslist.mccity,
          district: this.addresslist.mcdistrict,
          address: this.addresslist.address,
        },
        part_Category_Id: '',
        carPartDetails: this.SelectresultStr,
      }
      this.$api.accessory
        .addOrEditCarPart(params)
        .then((res) => {
          if (res.data) {
            this.$store.commit('accessory/cleanInfo')
            uni.showToast({
              title: '提交成功',
              duration: 2000,
            })
            setTimeout(() => {
              if (this.type === '0') {
                uni.redirectTo({
                  url: '/pages_findAccessory/myInquiryList/myInquiryList',
                })
              } else {
                uni.navigateBack()
              }
            }, 2000)
          } else {
            uni.showToast({
              title: '提交失败，请稍后重试',
              icon: 'none',
            })
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },

    //数据检查
    verifyData() {
      this.SelectresultStr = []
      for (let i = 0; i < this.Selectresult.length; i++) {
        if (!this.Selectresult[i].explain_Text) {
          uni.showToast({
            title: '说明不能为空，请补充',
            icon: 'none',
          })
          return false
        }
        let imgStr = ''
        if (this.Selectresult[i].images.length > 0) {
          imgStr = JSON.stringify(this.Selectresult[i].images)
        }
        this.SelectresultStr.push({
          id: this.Selectresult[i].id,
          explain_text: this.Selectresult[i].explain_Text,
          images: imgStr,
          part_category_id: this.Selectresult[i].part_Category_Id,
          part_category_name: this.Selectresult[i].part_Category_Name,
          purchase_number: this.Selectresult[i].purchase_Number,
        })
      }
      if (this.addresslist.address === '您还没有收货地址，请添加') {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none',
        })
        return false
      }

      if (!this.Production) {
        uni.showToast({
          title: '请选择有效期',
          icon: 'none',
        })
        return false
      }

      return true
    },
  },
}
